from fastapi import APIRouter, Depends, HTTPException, Query, Body
from sqlalchemy.orm import Session
from typing import List, Optional
from app.db.session import get_db
from app.db.models.user import User
from app.db.models.chat import RoomMember, Room
from app.utils.security import get_current_user
from app.schemas.common import APIResponse
from app.schemas.room import RoomCreate, RoomMemberAdd, RoomMemberQuery, PageResponse
from app.services.room import RoomService

router = APIRouter(prefix="/roomGroupUser", tags=["群组管理"])

@router.post("/create", summary="创建群聊")
async def create_room(
    data: RoomCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """创建群聊"""
    room_info = RoomService.create_room(
        db=db,
        user_id=current_user.id,
        name=data.name,
        description=data.description,
        avatar=data.avatar
    )
    
    return APIResponse(
        code=200,
        message="创建群聊成功",
        data=room_info
    )

@router.get("/list", summary="获取用户加入的群聊列表")
async def list_rooms(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取用户加入的群聊列表"""
    room_list = RoomService.get_user_rooms(db=db, user_id=current_user.id)
    
    return APIResponse(
        code=200,
        message="获取群聊列表成功",
        data=room_list
    )

@router.get("/detail/{id}", summary="获取群聊详情")
async def get_room_detail(
    id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取群聊详情"""
    room_info = RoomService.get_room_detail(db=db, room_id=id, user_id=current_user.id)
    
    if not room_info:
        raise HTTPException(status_code=404, detail="群聊不存在或您不是该群成员")
    
    return APIResponse(
        code=200,
        message="获取群聊详情成功",
        data=room_info
    )

@router.post("/invite", summary="邀请用户加入群聊")
async def invite_users(
    data: RoomMemberAdd,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """邀请用户加入群聊"""
    added_count = RoomService.invite_users(
        db=db,
        room_id=data.room_id,
        user_id=current_user.id,
        target_user_ids=data.user_ids
    )
    
    if added_count == 0:
        return APIResponse(
            code=400,
            message="邀请失败，请检查群聊ID或用户ID是否正确",
            data=None
        )
    
    return APIResponse(
        code=200,
        message=f"成功邀请{added_count}位用户加入群聊",
        data=None
    )

@router.post("/exit/{id}", summary="退出群聊")
async def exit_room(
    id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """退出群聊"""
    success = RoomService.exit_room(db=db, room_id=id, user_id=current_user.id)
    
    if not success:
        raise HTTPException(
            status_code=400,
            detail="退出群聊失败，可能是群聊不存在、您不是群成员或您是群主"
        )
    
    return APIResponse(
        code=200,
        message="退出群聊成功",
        data=None
    )

@router.delete("/{id}", summary="解散群聊")
async def disband_room(
    id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """解散群聊(群主)"""
    success = RoomService.disband_room(db=db, room_id=id, user_id=current_user.id)
    
    if not success:
        raise HTTPException(
            status_code=403,
            detail="解散群聊失败，可能是群聊不存在或您不是群主"
        )
    
    return APIResponse(
        code=200,
        message="解散群聊成功",
        data=None
    )

@router.get("/page", summary="分页获取群组成员")
async def get_group_member_page(
    room_id: int = Query(..., description="群聊房间ID"),
    page: int = Query(1, description="页码"),
    page_size: int = Query(20, description="每页数量"),
    keyword: Optional[str] = Query(None, description="搜索关键词"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """分页获取群组成员"""
    # 验证用户是否为群成员
    member = db.query(RoomMember).filter(
        RoomMember.room_id == room_id,
        RoomMember.user_id == current_user.id
    ).first()
    
    if not member:
        raise HTTPException(status_code=403, detail="您不是该群成员")
    
    members, total = RoomService.get_room_members(
        db=db, 
        room_id=room_id, 
        page=page, 
        page_size=page_size, 
        keyword=keyword
    )
    
    return APIResponse(
        code=200,
        message="获取群成员列表成功",
        data={
            "list": members,
            "total": total,
            "page": page,
            "page_size": page_size
        }
    )

@router.get("/count", summary="获取群组成员统计")
async def get_group_member_count(
    room_id: int = Query(..., description="群聊房间ID"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取群组成员统计"""
    # 验证用户是否为群成员
    member = db.query(RoomMember).filter(
        RoomMember.room_id == room_id,
        RoomMember.user_id == current_user.id
    ).first()
    
    if not member:
        raise HTTPException(status_code=403, detail="您不是该群成员")
    
    # 获取群成员总数
    total = db.query(RoomMember).filter(RoomMember.room_id == room_id).count()
    
    # 获取在线成员数
    online_count = db.query(User).join(
        RoomMember, User.id == RoomMember.user_id
    ).filter(
        RoomMember.room_id == room_id,
        User.online == True
    ).count()
    
    return APIResponse(
        code=200,
        message="获取群成员统计成功",
        data={
            "total": total,
            "online": online_count
        }
    )

@router.get("/search", summary="搜索群聊")
async def search_rooms(
    keyword: str = Query(..., description="搜索关键词"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """搜索群聊"""
    try:
        rooms = RoomService.search_groups(
            db=db,
            keyword=keyword,
            user_id=current_user.id
        )
        
        return APIResponse(
            code=200,
            message="搜索群聊成功",
            data=rooms
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail={"message": f"搜索群聊失败: {str(e)}"})

@router.post("/join/{id}", summary="申请加入群聊")
async def join_room(
    id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """申请加入群聊"""
    try:
        success = RoomService.join_group(
            db=db,
            room_id=id,
            user_id=current_user.id
        )
        
        if not success:
            return APIResponse(
                code=400,
                message="申请加入群聊失败，可能是群聊不存在",
                data=None
            )
        
        return APIResponse(
            code=200,
            message="已发送加入申请，请等待群主审核",
            data=None
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail={"message": f"申请加入群聊失败: {str(e)}"})

@router.post("/apply/review", tags=["群聊管理"])
async def review_join_apply(
    data: dict = Body(..., example={"id": 123, "status": 1}),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """审核群聊加入申请
    
    - **id**: 申请ID
    - **status**: 审核状态 1-通过 2-拒绝
    """
    if not isinstance(data.get("id"), int) or not isinstance(data.get("status"), int):
        return {"code": 400, "message": "参数错误", "data": None}
        
    if data["status"] not in [1, 2]:
        return {"code": 400, "message": "状态值无效", "data": None}
        
    result = RoomService.review_join_apply(
        db=db,
        apply_id=data["id"],
        user_id=current_user.id,
        status=data["status"]
    )
    
    if not result:
        return {"code": 400, "message": "操作失败，申请不存/您没有权限/申请被处理", "data": None}
        
    return {"code": 0, "message": "操作成功", "data": None}

@router.get("/applies", tags=["群聊管理"])
async def get_room_applies(
    room_id: int = Query(..., description="群聊ID"),
    status: int = Query(0, description="申请状态 0-待审核 1-已通过 2-已拒绝"),
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取群聊申请列表"""
    # 检查用户是否有权限（是否为群主或管理员）
    room_member = db.query(RoomMember).filter(
        RoomMember.room_id == room_id,
        RoomMember.user_id == current_user.id,
        RoomMember.role.in_([1, 2])  # 1-管理员 2-群主
    ).first()
    
    if not room_member:
        return {"code": 403, "message": "您没有权限查看申请列表", "data": None}
        
    try:
        applies, total = RoomService.get_room_applies(
            db=db,
            room_id=room_id,
            status=status,
            page=page,
            page_size=page_size
        )
        
        return {
            "code": 0,
            "message": "获取成功",
            "data": {
                "list": applies,
                "total": total,
                "page": page,
                "page_size": page_size
            }
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail={"message": f"获取申请列表失败: {str(e)}"})

@router.get("/user/applies", summary="获取用户的群聊申请列表")
async def get_user_room_applies(
    status: int = Query(0, description="申请状态 0-待审核 1-已通过 2-已拒绝"),
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取用户的群聊申请列表，包括：
    1. 用户发起的申请
    2. 用户作为群主或管理员接收到的申请
    """
    try:
        from app.db.models.user import Apply
        
        # 1. 获取用户发起的群聊申请
        user_applies_query = db.query(Apply, User).join(
            User, Apply.applicant_id == User.id
        ).filter(
            Apply.applicant_id == current_user.id,
            Apply.type == 1,  # 群聊申请，修改为1以匹配join_group函数
            Apply.status == status
        )
        
        # 2. 获取用户作为群主或管理员的群聊ID列表
        managed_rooms = db.query(RoomMember.room_id).filter(
            RoomMember.user_id == current_user.id,
            RoomMember.role.in_([1, 2])  # 1-管理员 2-群主
        ).all()
        managed_room_ids = [room.room_id for room in managed_rooms]
        
        # 3. 获取这些群聊的申请
        received_applies_query = None
        if managed_room_ids:
            received_applies_query = db.query(Apply, User).join(
                User, Apply.applicant_id == User.id
            ).filter(
                Apply.room_id.in_(managed_room_ids),
                Apply.type == 1,  # 群聊申请，修改为1以匹配join_group函数
                Apply.status == status
            )
            
        # 4. 合并查询结果
        if received_applies_query:
            # 如果有管理的群聊，合并两个查询
            combined_query = user_applies_query.union(received_applies_query)
        else:
            # 如果没有管理的群聊，只使用用户申请查询
            combined_query = user_applies_query
            
        # 计算总数
        total = combined_query.count()
        
        # 分页并排序
        applies = combined_query.order_by(Apply.created_at.desc()).offset((page - 1) * page_size).limit(page_size).all()
        
        # 构建返回数据
        apply_list = []
        for apply, user in applies:
            # 获取群聊信息
            room = db.query(Room).filter(Room.id == apply.room_id).first()
            
            apply_list.append({
                "id": apply.id,
                "userId": user.id,
                "nickname": user.nickname,
                "avatar": user.avatar,
                "roomId": apply.room_id,
                "roomName": room.name if room else "未知群聊",
                "roomAvatar": room.avatar if room else "",
                "content": apply.content,
                "status": apply.status,
                "createdAt": apply.created_at.strftime("%Y-%m-%d %H:%M:%S") if apply.created_at else "",
                "isApplicant": apply.applicant_id == current_user.id  # 标记是否为申请人
            })
            
        return APIResponse(
            code=200,
            message="获取群聊申请列表成功",
            data={
                "list": apply_list,
                "total": total,
                "page": page,
                "page_size": page_size
            }
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail={"message": f"获取群聊申请列表失败: {str(e)}"})